package org.activiti.DelegateTasks;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.apache.log4j.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Slejus
 * Date: 13.11.15
 * Time: 11.38
 * To change this template use File | Settings | File Templates.
 */

public class InflectionDelegateTask implements JavaDelegate{

    private static final Logger logger = Logger.getLogger(InflectionDelegateTask.class);

    @Override
    public void execute(DelegateExecution execution) throws Exception {

        String fullName = (String) execution.getVariable("initiatorFullName");
        logger.debug("LastName: " + fullName);
        String position = (String) execution.getVariable("initiatorPosition");
        logger.debug("JobTitle: " + position);
        String division = (String) execution.getVariable("initiatorDivision");
        logger.debug("Organization: " + division);

        String fullNameGen = inflectPersonInfo(fullName, Case.GENITIVE, true);
        logger.debug("lastNameGen: " + fullName);
        String fullNameDat = inflectPersonInfo(fullName, Case.DATIVE, true);
        logger.debug("lastNameDat: " + fullName);
        String positionGen = inflectPersonInfo(position, Case.GENITIVE, true);
        logger.debug("jobTitleGen: " + position);
        String positionDat= inflectPersonInfo(position, Case.DATIVE, true);
        logger.debug("jobTitleDat: " + position);
        String divisionGen = inflectPersonInfo(division, Case.GENITIVE, false);
        logger.debug("organizationGen: " + division);
        String divisionDat = inflectPersonInfo(division, Case.DATIVE, false);
        logger.debug("organizationDat: " + division);

        execution.setVariable("initiatorFullNameGen", fullNameGen);
        execution.setVariable("initiatorPosition", positionGen);
        execution.setVariable("initiatorDivisionGen", divisionGen);

    }

    private String inflectPersonInfo(String str, Case wordCase, boolean inflectAllStringWords) {
        String result = "";
        String[] parts = str.split("[,\\s\\-:\\?]");
        int size = parts.length;
        if (inflectAllStringWords) {
            for (int i = 0; i < size; i++) {
                result += Inflector.getCasedWord(parts[i], wordCase);
                if (i != size-1) {
                    result += " ";
                }
            }
        } else {
            String lastWord = parts[size - 1];
            lastWord = Inflector.getCasedWord(lastWord, wordCase);
            parts[size-1] = lastWord;
            for (int i = 0; i < size; i++) {
                result += parts[i];
                if (i != size-1) {
                    result += " ";
                }
            }
        }
        return result;
    }
}
